package com.iflyteck.service.impl;

import com.iflyteck.pojo.Comment;
import com.iflyteck.repository.CommentRepository;
import com.iflyteck.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Optional;
import java.util.concurrent.TimeUnit;

@Service
public class ApiCommentServiceImpl implements CommentService {
    @Autowired
    private CommentRepository commentRepository;

    @Autowired
    private RedisTemplate redisTemplate;

    // 使用api方式进行缓存：先去缓存中查找，缓存中有，直接返回，没有则查询数据库
    public Comment findCommentById(Integer id) {
        Object obj = redisTemplate.opsForValue().get("comment_" + id);
        if (obj != null) {
            // 查询到数据 直接返回
            return (Comment) obj;
        } else {
            Optional<Comment> optional = commentRepository.findById(id);
            if (optional.isPresent()) {
                // 将数据库查询结果存入缓存中 设置有效期为一天
                Comment comment = optional.get();
                redisTemplate.opsForValue().set("comment_" + id, comment,1, TimeUnit.DAYS);
                return comment;
            }
        }
        return null;
    }

    public Comment updateComment(Comment comment){
        commentRepository.updateComment(comment.getAuthor(), comment.getId());
        // 将更新数据进行缓存更新
        redisTemplate.opsForValue().set("comment_" + comment.getId(),comment, 1,TimeUnit.DAYS);
        return comment;
    }

    public void deleteComment(Integer id) {
        commentRepository.deleteById(id);
        redisTemplate.delete("comment_" + id);
    }

}
